package com.ktjiaoyu.t313.controller;

import com.ktjiaoyu.t313.exception.LoginException;
import com.ktjiaoyu.t313.pojo.SysUser;
import com.ktjiaoyu.t313.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 去到登录页面
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){

        return "login";

    }

    /**
     * 处理登录请求
     * @param account
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(Model model, String account, String password, HttpSession session) throws LoginException {

        //调用查询，校验用户名密码是否正确
        SysUser user = userService.login(account,password);

        if(user == null){
            throw new LoginException("用户名或密码不正确！");
        }

        if(user != null){
            //表示用户登录成功
            session.setAttribute("userSession",user);   //将用户信息存入session
            return "frame";
        }else{
            model.addAttribute("error","用户名或密码错误！请重试！");
            return "login";
        }
    }

    @RequestMapping("/logout")
    public String loginOut(HttpSession session){

        session.invalidate();//session失效
        if(1==1){
            throw new RuntimeException("退出登录发生异常！！");
        }
        return "login";
    }

    /**
     * 局部异常处理
     * @param e
     * @param req
     * @return
     */
    /*@ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req){
        req.setAttribute("e",e);
        return "sysError";
    }*/

}
